﻿/***********************************
//习题管理模块
***********************************/

Ext.namespace('EHSubmit.Goal.Question');

//-----搜索结果中选定的记录的索引
EHSubmit.Goal.Question.selectedRecIndex = null;

///----用于存放要作为作业的习题-----
EHSubmit.Goal.Question.qesStore = new Ext.data.Store({
    //id:'qesStore',
    sortInfo: {
        field: 'Type',
        direction: 'ASC'   // or 'DESC' (case sensitive for local sorting)
    },
    reader: new Ext.data.JsonReader({
        //totalProperty: 'count',    //总记录个数
        root: 'data',
    },
    [   // 数据模型
        { name: 'QID' },
        { name: 'OwnerID' },
        //{ name: 'OwnerName'},
        { name: 'Type'},
        { name: 'Content'},
        { name: 'Answer'},
        { name: 'UpdateTime' },
        { name: 'RightCount'},
        { name: 'WrongCount' },
        { name: 'Rate' },
        { name: 'Institute'},    
        { name: 'Department'},
        { name: 'Options'}
    ])
})

//刷新浏览习题界面
EHSubmit.Goal.Question.preview = function(){
    //添加习题至预览
    var qesPreviewForm = Ext.getCmp('qesPreviewForm');
    qesPreviewForm.removeAll(true);
    var store = EHSubmit.Goal.Question.qesStore;
    //---按题型排序
    store.sort('Type','ASC');
    for (var i=0;i < store.getCount();i++){
        var data = store.getAt(i).data;
        qesPreviewForm.add(new Ext.ux.Question({qType:data.Type, order:i+1, qTitle:data.Content, qId: data.QID, qBody:data.Options}));
    }
    //窗体重新布局
    qesPreviewForm.doLayout();
}


EHSubmit.Goal.Question.addQes = function(){
//    var singleValue = Ext.getCmp('ansFieldset').getComponent('singleAnsGroup').getValue();
//    var multiValue = Ext.getCmp('ansFieldset').getComponent('multiAnsGroup').getValue();

    //-----选项类-----
    function Option(label,content){
        this.Label = label;
        this.Content = content;
    }
    var singleOption = new Array();
    var multiOption = new Array();
    var label = null;
    var content = null;
    var hasAnswer = false;
    var isIdentical = false;
    var i,j;
    var frm = Ext.getCmp('addQesForm');
    var typeChoice = Ext.getCmp('typeChoice');
    var tempSingleAnsID = null;
    var tempMultiAnsID = null;
    var tempAnsContentID = null;
    var optionJson = null;

    var groupID = typeChoice.getValue().getItemId();
    switch(groupID){
        case 'single':{
            for (i = 0 ; i < 4 ; i++){
                tempSingleAnsID = 'singleAns' + (i+1);
                tempAnsContentID = 'ansContent' + (i+1);
                //---判断是否有单选答案------
                if(!hasAnswer && Ext.getCmp(tempSingleAnsID).checked){
                    hasAnswer = true;
                }
                label = Ext.getCmp(tempSingleAnsID).inputValue;
                content = Ext.getCmp(tempAnsContentID).getValue().trim();
                var single = new Option(label,content);
                singleOption.push(single);
            }
            
            //---判断是否有相同选项-----
            for(i = 0 ; i < 4 ; i++){
                for(j = i + 1 ; j < 4 ; j++){
                    if(singleOption[i].Content == singleOption[j].Content){
                        isIdentical = true;
                        break;
                    }
                }
                if(isIdentical){
                    break;
                }
            }
            
            //---题目选项转为json
            optionJson = Ext.util.JSON.encode(singleOption);
            break;
        }
        case 'multiple':{
            for(i = 0 ; i < 4 ; i++){
                tempMultiAnsID = 'multiAns' + (i+1);
                tempAnsContentID = 'ansContent' + (i+1);
                //---判断多选是否有答案
                if(!hasAnswer && Ext.getCmp(tempMultiAnsID).checked){
                    hasAnswer = true;
                }
                label = Ext.getCmp(tempMultiAnsID).inputValue;
                content = Ext.getCmp(tempAnsContentID).getValue().trim();
                var multi = new Option(label,content);
                multiOption.push(multi);
            }
            
            //---判断是否有相同选项-----
            for(i = 0 ; i < 4 ; i++){
                for(j = i + 1 ; j < 4 ; j++){
                    if(multiOption[i].Content == multiOption[j].Content){
                        isIdentical = true;
                        break;
                    }
                }
                if(isIdentical){
                    break;
                }
            }
            //---题目选项转为json
            optionJson = Ext.util.JSON.encode(multiOption);
            break;
        }            
    }
    
    //-----判断老师是否已填写答案-------
    if(hasAnswer && !isIdentical){
        if (frm.getForm().isValid()) {  //验证
            frm.getForm().submit({  //提交
                url: EHSubmit.ajaxRoot + 'QuestionHandler.ashx?Op=addQes',
                waitTitle: '等待',
                waitMsg: '正在提交，请稍后...',
                method: 'POST',
                params: {
                    opts: optionJson,
                },
                success: function(form, action) {
                    var successed = action.result.success;
                    if (successed) {
                        ///////////////  提交成功处理  ///////////////////
                        Ext.MessageBox.alert('提示', action.result.msg);
                        
                        EHSubmit.Goal.Question.qesStore.loadData(action.result,true);
                        //刷新浏览习题界面
                        EHSubmit.Goal.Question.preview();
				        //----关闭当前窗口---------
                        var addQesWin = Ext.getCmp('addQesWin');
                        addQesWin.close();
//                        var a = EHSubmit.Goal.Question.qesStore.getAt(0).data;
//                        var b = a.Options[1].QID;

                    }
                    else {
                        Ext.MessageBox.alert('失败', '信息:' + action.result.msg);
                    }
                },
                failure: function(form, action) {
                    var errmsg = null;
                    switch (action.failureType) {
                        case Ext.form.Action.CLIENT_INVALID:
                            errmsg = 'Form fields may not be submitted with invalid values';
                            break;
                        case Ext.form.Action.CONNECT_FAILURE:
                            errmsg = 'Ajax communication failed';
                            break;
                        case Ext.form.Action.SERVER_INVALID:
                            errmsg = action.result.msg;
                    }
                    Ext.MessageBox.alert('错误', errmsg);
                }   // failure  
            })
        }
    }
    else{
        if(!hasAnswer){
            Ext.MessageBox.alert('错误','标准答案未知!');
        }
        else{
            Ext.MessageBox.alert('错误','选项不能相同!');
        }
    }
}


//-------包含写信息窗口的容器--------------
EHSubmit.Goal.Question.addQesWin = {
    id: 'addQesWin',
    title: '添加习题窗口',
    //xtype:'window',
    width: 680,
    height: 450,
    plain: true,
    border: false,
    layout: 'fit',
    modal: true,

    //-------topbar-------
    tbar: [{
        text: '添加至该作业',
        tooltip: '添加至该作业',
        iconCls: 'accept',
        handler: EHSubmit.Goal.Question.addQes
    }, '-', {
        text: '取消',
        tooltip: '取消',
        iconCls: 'close',
        handler: function() {
            //----关闭当前窗口---------
            var addQesWin = Ext.getCmp('addQesWin');
            addQesWin.close();
        }
    }],

    items: [{
        xtype:'form',
        id:'addQesForm',
        layout:'vbox',
        //labelAlign:'top',
        layoutConfig: {
            align : 'stretch',
            pack  : 'start'
        },
        items:[{
            //-----上半部分---------
            xtype:'panel',
            //id:'uppanel',
            flex:0.8,
            layout: 'column',
            frame:true,
            border: false,
            // defaults are applied to all child items unless otherwise specified by child item
            defaults: {
                //columnWidth: '.5',
                border: false,
                frame:false,
                height:450
            },            
            items:[{
                //-------第一列，题目类型-----
                //bodyStyle: 'padding:5px 0 5px 5px;',
                columnWidth:'.7',
                items: {
                    xtype: 'fieldset',
                    title: '题目类型',
                    border: false,
                    autoHeight: true,
                    items:{
                        id: 'typeChoice',
                        xtype: 'radiogroup',
                        hideLabel: true,
                        items: [
                            { itemId: 'single', boxLabel: '单选题', name: 'qesTypeRadio', inputValue:'0',checked: true },
                            { itemId: 'multiple', boxLabel: '多选题', name: 'qesTypeRadio',inputValue:'1' },
                            { itemId: 'judge', boxLabel: '判断题(待实现)', name: 'qesTypeRadio',inputValue:'2' },
                            { itemId: 'blank', boxLabel: '填空题(待实现)', name: 'qesTypeRadio',inputValue:'3' }
                        ],
                        listeners:{
                            //--------单选与多选的切换，都要reset--------
                            change: function(thisRdGroup, checkedRd) {
                                var groupID = checkedRd.getItemId();
                                var i;
                                //var ansFieldset = Ext.getCmp('ansFieldset');
                                //var singleAns = Ext.getCmp('singleAns1').getGroupValue();
                                //var multiAnsGroup = ansFieldset.getComponent('multiAnsGroup');
                                //-----重置选项-----
                                for (i = 0 ; i < 4 ; i++){
                                    var tempSingleAnsID = 'singleAns' + (i+1);
                                    var tempMultiAnsID = 'multiAns' + (i+1);
                                    var tempAnsContentID = 'ansContent' + (i+1);
                                    Ext.getCmp(tempSingleAnsID).reset();
                                    Ext.getCmp(tempMultiAnsID).reset();
                                    Ext.getCmp(tempAnsContentID).reset();                                    
                                }
                                
                                switch (groupID) {
                                    //--单选
                                    case 'single':
                                        {
//                                            singleAnsGroup.show();  //hidden值
//                                            singleAnsGroup.reset();
//                                            multiAnsGroup.hide();
//                                            multiAnsGroup.reset();
                                            Ext.getCmp('choicePanel').show();
                                            Ext.getCmp('judgePanel').hide();
                                            Ext.getCmp('blankPanel').hide();
                                            
                                            for (i = 0 ; i < 4 ; i++){
                                                var tempSingleAnsID = 'singleAns' + (i+1);
                                                var tempMultiAnsID = 'multiAns' + (i+1);
                                                var tempAnsContentID = 'ansContent' + (i+1);
                                                Ext.getCmp(tempSingleAnsID).show();
                                                Ext.getCmp(tempMultiAnsID).hide();                              
                                            }
                                            break;
                                        }
                                    //--多选
                                    case 'multiple':
                                        {
                                            Ext.getCmp('choicePanel').show();
                                            Ext.getCmp('judgePanel').hide();
                                            Ext.getCmp('blankPanel').hide();

                                            for (i = 0 ; i < 4 ; i++){
                                                var tempSingleAnsID = 'singleAns' + (i+1);
                                                var tempMultiAnsID = 'multiAns' + (i+1);
                                                var tempAnsContentID = 'ansContent' + (i+1);
                                                Ext.getCmp(tempSingleAnsID).hide();
                                                Ext.getCmp(tempMultiAnsID).show();                              
                                            }
                                            break;
                                        }
                                     //--判断
                                     case 'judge':
                                         {
                                            Ext.getCmp('choicePanel').hide();
                                            Ext.getCmp('judgePanel').show();
                                            Ext.getCmp('blankPanel').hide();
                                            break;
                                         }
                                     //--填空
                                     case 'blank':
                                         {
                                            Ext.getCmp('choicePanel').hide();
                                            Ext.getCmp('judgePanel').hide();
                                            Ext.getCmp('blankPanel').show();

                                            break;
                                         }    
                                }
                            }
                        }
                    }
                }
//            }, {
//                //-------第二列，题目适用范围-----
//                //bodyStyle: 'padding:5px 5px 5px 5px;',
//                columnWidth:'.6',
//                items: {
//                    xtype: 'fieldset',
//                    id:'scopeFieldSet',
//                    border: false,
//                    title:'题目适用范围',
//                    autoHeight: true,
//                    labelWidth:50,
//                    items: [{
//                        xtype: 'combo',
//                        itemId:'instituteCombo',
//                        //name: 'institute',
//                        fieldLabel: '学院',
//                        editable: false,
//                        emptyText: '请选择...',
//                        blankText:'请选择...',
//                        allowBlank:false,
//                        mode: 'remote',
//                        triggerAction: 'all',
//                        selectOnFocus: true,
//                        valueField: 'instituteID',
//                        displayField: 'instituteName',

//                        store: new Ext.data.JsonStore({
//                            storeId: 'instituteStore',
//                            //autoLoad: true,
//                            baseParams: { Op: 'List_Institute' },     //根据教师id获取其教的课程
//                            proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'QuestionHandler.ashx' }),  //后台具体处理

//                            root: 'institutes',
//                            fields: [
//                                { name: 'instituteID', mapping: 'InstituteID' },
//                                { name: 'instituteName', mapping: 'InstituteName' }
//                            ]
//                        }),

//                        listeners: {
//                            select: function(combo, record, index) {
//                                //根据学院Id获取专业信息
//                                var a = Ext.getCmp('scopeFieldSet').getComponent('deptCombo').clearValue();
//                                Ext.getCmp('scopeFieldSet').getComponent('deptCombo').enable();
//                                
//                                //----给习题库添加新习题时需要------
//                                Ext.getCmp('instituteHidden').setValue(Ext.getCmp('scopeFieldSet').getComponent('instituteCombo').getValue());
//                            }
//                        }
//                    },{
//                        xtype: 'combo',
//                        itemId:'deptCombo',
//                        //name: 'department',
//                        fieldLabel: '专业',
//                        disabled: true,     //初始化时不可用，选择课程后可用
//                        editable: false,
//                        emptyText: '请选择...',
//                        blankText:'请选择...',
//                        allowBlank:false,
//                        mode: 'local',
//                        pruneModifiedRecords:true,
//                        triggerAction: 'all',
//                        autoSelect:false,
//                        selectOnFocus: true,
//                        valueField: 'deptID',
//                        displayField: 'deptName',

//                        store: new Ext.data.JsonStore({
//                            storeId: 'deptStore',
//                            autoLoad: false,
//                            baseParams: { Op: 'List_Depts', insID: '' },
//                            proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'QuestionHandler.ashx' }),  //后台具体处理
//                            pruneModifiedRecords:true,
//                            totalProperty: 'total',    //总记录个数
//                            root: 'depts',
//                            fields: [
//                                { name: 'deptID', mapping: 'DepartmentID' },
//                                { name: 'deptName', mapping: 'DepartmentName' }
//                            ],
//                            listeners:{
//                                beforeload:function(thisStore){
//                                    thisStore.removeAll();
//                                },
//                                load:function(thisStore,records){
//                                    //----判断有无数据---------
//                                    var deptCombo = Ext.getCmp('scopeFieldSet').getComponent('deptCombo');
//                                    if(thisStore.getTotalCount() == 0){
//                                        //deptCombo.disable();
//                                        deptCombo.markInvalid('无相关数据!');
//                                    }
//                                    else{
//                                        deptCombo.setValue('请选择...');
//                                    }
//                                }
//                            }
//                        }),

//                        listeners: {
//                            enable: function(combo) {
//                                //将学院id传给服务器端
//                                var store = combo.getStore();
//                                var insID = Ext.getCmp('scopeFieldSet').getComponent('instituteCombo').getValue();
//                                store.setBaseParam('insID',insID);
//                                store.load();
//                            },
//                            select: function(combo, record, index) {
//                                //----给习题库添加新习题时需要------
//                                Ext.getCmp('departmentHidden').setValue(Ext.getCmp('scopeFieldSet').getComponent('deptCombo').getValue());
//                            }
//                        }
//                    }]
//                }
            }]
        },{
            //-----中间部分------------
            xtype:'panel',
            layout:'fit',
            border:false,
            flex:1,
            items:{
                xtype:'textarea',
                emptyText: '此处请填写习题题目',
                name:'qesContent',
                hideLabel:false,
                allowBlank:false,
                blankText: '填写习题题目',
           }
        },{
            //---下面部分(三部分：choicePanel/judgePanel/blankPanel)--------
            xtype:'panel',
            border:false,
            frame:true,
            bodyStyle: 'padding:10px 0 10px 0;',
            flex:2,
            items:[
            {
                xtype:'panel',
                id:'choicePanel',
    //            border:false,
    //            frame:true,
    //            bodyStyle: 'padding:10px 0 10px 0;',
                items:[{
                    xtype:'fieldset',
                    id:'ansFieldset',
                    title: '习题选项及答案',
                    anchor: '100%',
                    border: false,
                    hideLabel:true,           
                    items:[{
                        xtype:'compositefield',
                        defaultMargins: '0 5 0 20',
                        hideLabel:true,    
                        items:[{
                            xtype:'radio',
                            boxLabel:'A',
                            id:'singleAns1',
                            name:'singleAns',
                            inputValue:'A',
                        },{
                            xtype:'checkbox',
                            id:'multiAns1',
                            name: 'multiAns',
                            hidden:true,
                            boxLabel:'A',
                            inputValue:'A'
                        },{
                            xtype:'textfield',
                            id:'ansContent1',
                            //name:'ansContent1',
                            allowBlank:false,
                            blankText:'请输入选项内容!',
                            flex:1,
                            hideLabel:true,
                        }]
                    },{
                        xtype:'compositefield',
                        defaultMargins: '0 5 0 20',
                        border: false,
                        hideLabel:true,    
                        items:[{
                            xtype:'radio',
                            boxLabel:'B',
                            id:'singleAns2',
                            name:'singleAns',
                            inputValue:'B'
                        },{
                            xtype:'checkbox',
                            id:'multiAns2',
                            name: 'multiAns',
                            hidden:true,
                            boxLabel:'B',
                            inputValue:'B'
                        },{
                            xtype:'textfield',
                            id:'ansContent2',
                            //name:'ansContent2',
                            allowBlank:false,
                            blankText:'请输入选项内容!',
                            hideLabel:true,
                            flex:1,
                        }]
                    },{
                        xtype:'compositefield',
                        defaultMargins: '0 5 0 20',
                        border: false,
                        hideLabel:true,    
                        items:[{
                            xtype:'radio',
                            boxLabel:'C',
                            id:'singleAns3',
                            name:'singleAns',
                            inputValue:'C'
                        },{
                            xtype:'checkbox',
                            id:'multiAns3',
                            name: 'multiAns',
                            hidden:true,
                            boxLabel:'C',
                            inputValue:'C'
                        },{
                            xtype:'textfield',
                            id:'ansContent3',
                            //name:'ansContent3',
                            allowBlank:false,
                            blankText:'请输入选项内容!',
                            hideLabel:true,
                            flex:1
                        }]
                    },{
                        xtype:'compositefield',
                        defaultMargins: '0 5 0 20',
                        border: false,
                        hideLabel:true,    
                        items:[{
                            xtype:'radio',
                            boxLabel:'D',
                            id:'singleAns4',
                            name:'singleAns',
                            inputValue:'D'
                        },{
                            xtype:'checkbox',
                            id:'multiAns4',
                            name: 'multiAns',
                            hidden:true,
                            boxLabel:'D',
                            inputValue:'D'
                        },{
                            xtype:'textfield',
                            id:'ansContent4',
                            //name:'ansContent4',
                            allowBlank:false,
                            blankText:'请输入选项内容!',
                            hideLabel:true,
                            flex:1
                        }]
                    }]
                }]
            },  //choicePanel end
            {
                xtype:'panel',
                id:'judgePanel',
                layout: 'column',
                frame:false,
                border: false,
                bodyStyle: 'padding:0 0 0 8px;',
                hidden:true,
                items:[{
                    xtype:'fieldset',
                    //id:'ansFieldset',
                    title: '习题答案',
                    columnWidth: '.3',
                    border: false,
                    hideLabel:true,
                    items:{
                        xtype: 'radiogroup',
                        hideLabel: true,
                        items: [
                            { itemId: 'yes', boxLabel: '对', name: 'judgeRadio', inputValue:'0' },
                            { itemId: 'no', boxLabel: '错', name: 'judgeRadio',inputValue:'1' }
                        ]
                    }
                }]
            }, //judgePanel end
            {
                xtype:'panel',
                id:'blankPanel',
                //layout: 'column',
                frame:false,
                border: false,
                //bodyStyle: 'padding:0 0 0 8px;',

                hidden:true,
                items:[{
                    xtype:'fieldset',
                    //id:'ansFieldset',
                    title: '习题答案(注:如果存在多个答案,请用逗号分隔。如答案一，答案二)',
                    //columnWidth: '1',
                    border: false,
                    hideLabel:true,
                    items:[{
                        xtype:'textfield',
                        width:'95%',
                        hideLabel:true,
                        allowBlank:false,
                        disabled:true,
                        value:'默认值'
                    }]
                }]
            }   //blankPanel end
            ]  //---下面部分(三部分：choicePanel/judgePanel/blankPanel) items end--------
        },   //---下面部分(三部分：choicePanel/judgePanel/blankPanel) end--------
        {
            xtype: 'hidden',
            id:'baseCourseIDHidden',
            name: 'BaseCourseID'
//        },{
//            xtype: 'hidden',
//            id:'instituteHidden',
//            name:'institute'
//        },{
//            xtype: 'hidden',
//            id:'departmentHidden',
//            name:'department'
        }] 
    }],

    //-------footbar--------------
    fbar: [{
        text: '添加至该作业',
        tooltip: '添加至该作业',
        iconCls: 'accept',     //图标引用需写在css中
        handler: EHSubmit.Goal.Question.addQes
    }, '-', {
        text: '取消',
        tooltip: '取消',
        iconCls: 'close',
        handler: function() {
            //----关闭当前窗口---------
            var addQesWin = Ext.getCmp('addQesWin');
            addQesWin.close();
        }
    }],
    
    listeners:{
        activate:function(){
            //----给习题库添加新习题时需要------
            Ext.getCmp('baseCourseIDHidden').setValue(EHSubmit.Goal.Question.BaseCourseID);
        }
    }
}